package com.beiding.listener;

import com.beiding.dao.EvaluationDao;
import com.beiding.dao.RoomDao;
import com.beiding.pojo.Room;
import com.beiding.service.StaticResourceService;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Component
public class RoomListener extends AbstractMongoDBListener<Room> {


    private StaticResourceService resourceService;

    private RoomDao roomDao;

    private EvaluationDao evaluationDao;

    public RoomListener(StaticResourceService resourceService, RoomDao roomDao, EvaluationDao evaluationDao) {
        this.resourceService = resourceService;
        this.roomDao = roomDao;
        this.evaluationDao = evaluationDao;
    }

    @Override
    protected void onSave(Room obj) {

        Set<String> images = obj.getImages();

        if (images != null) {
            List<String> shouldClaim = new ArrayList<>();
            List<String> shouldDel = new ArrayList<>();

            images.removeIf(s -> {

                if (s.startsWith("d-")) {
                    shouldDel.add(s.substring(2));
                    return true;
                } else if (s.startsWith("a-")) {
                    shouldClaim.add(s.substring(2));
                    return true;
                }
                return false;
            });


            if (shouldClaim.size() > 0) {
                //批量认领
                List<String> suc = resourceService.claim(shouldClaim);
                images.addAll(suc);
            }
            if (shouldDel.size() > 0) {
                //移除被认领的资源
                List<String> suc = resourceService.remove(shouldDel);
                //将没有被成功移除的资源再加入images中
                shouldDel.removeAll(suc);
                images.addAll(shouldDel);
            }

            images.forEach(System.out::println);

        }
    }

    @Override
    protected void onDelete(String id) {
        Optional<Room> optional = roomDao.findByIdLimitFields(id, "images");
        if (optional.isPresent()) {
            Room room = optional.get();

            String roomId = room.getId();

            evaluationDao.deleteByHolder(roomId);

            Set<String> images = room.getImages();
            if (images != null && images.size() > 0) {
                resourceService.remove(Lists.newArrayList(images));
            }
        }
    }
}
